<template>
	<baseDialog ref="dialogRef" :title="dialogTitle" width="600px" @confirm="handleSubmit" @close="handleClose">
		<el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
			<el-form-item label="键：" prop="key">
				<div class="w-80">
					<el-input v-model="formData.key" placeholder="请输入键" disabled  clearable />
				</div>
			</el-form-item>
			<el-form-item label="值：" prop="value">
				<div class="w-80">
					<el-input v-model="formData.value" type="textarea" :autosize="{ minRows: 6, maxRows: 4 }" placeholder="请输入值" />
				</div>
			</el-form-item>
			<el-form-item label="有效期：" prop="time">
				<div>
					<el-input v-model="formData.time" type="number" placeholder="请输入有效期"  clearable >
						<template #append>秒</template>
					</el-input>
					<div class="el-form-tips">为空或0表示永不过期</div>
				</div>
			</el-form-item>
		</el-form>
	</baseDialog>
</template>

<script setup lang="ts" name="redisEdit">
import { ref, shallowRef, reactive, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { messageSuccess } from '/@/utils/message';
import { dbRedisDetail, dbRedisEdit } from '/@/api/setting/db';

const dialogRef = ref(null);

const dialogType = ref('edit');

const dialogTitle = computed(() => {
	return '编辑缓存';
});

const emit = defineEmits(['submit', 'close']);

const formRef = shallowRef<FormInstance>();

const formData = reactive({
	key: '',
	value: '',
	time: '',
});

const rules = reactive({
	value: [{ required: true, message: '请输入值', trigger: ['blur'] }],
	time: [{ required: true, message: '请输入有效期', trigger: ['blur'] }],
});

const handleSubmit = async () => {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return;
		await dbRedisEdit(formData);
		dialogRef.value?.close();
		messageSuccess('编辑成功')
		emit('submit');
	});
};

const setFormData = async (row: any, callback: any) => {
	const data = await dbRedisDetail({
		key: row.key,
	});

	for (const key in formData) {
		if (data[key] != null && data[key] != undefined) {
			formData[key] = data[key];
		}
	}
	callback();
};

const handleClose = () => {
	emit('close');
};

const open = (type = 'edit') => {
	dialogType.value = type;
	dialogRef.value?.open();
};

defineExpose({
	open,
	setFormData
});
</script>
